package io.hilo.example.demo.metric;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.stereotype.Component;

import org.hilo.boot.core.UT;
import org.hilo.boot.core.spring.AsyncRunAfterStart;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.ImmutableTag;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;

/**
 * Gauge表示任意单个上下移动的数值测量。
 *  通常用于变动的测量值，如当前的内存使用情况，同时也可以测量上下移动的"计数"，比如队列中的消息数量。
 * @author zollty
 * @since 2020年9月17日
 */
@Component
public class PassCaseMetric implements AsyncRunAfterStart {
    
    Gauge passCaseGuage;
    AtomicInteger passCases;
    
    public PassCaseMetric(MeterRegistry registry) {
        passCases = registry.gauge("app.pass.cases.guage.value", init(), atomicInteger);
        
//        passCaseGuage = Gauge.builder("pass.cases.guage", atomicInteger, AtomicInteger::get)
//                .tag("service", "demo").description("pass cases guage of demo")
//                .register(registry);
        
         passCaseGuage = registry.find("app.pass.cases.guage.value").gauge();
    }

    List<Tag> init() {
        ArrayList<Tag> list = new ArrayList<Tag>();
        list.add(new ImmutableTag("service", "demo"));
        return list;
    }

    // atomicInteger 为数据源
    // Gauge用来测量，它引用了数据源
    // passCases用来包装数据源？
    
    AtomicInteger atomicInteger = new AtomicInteger(0);

//    Gauge passCaseGuage = Gauge.builder("pass.cases.guage", atomicInteger, AtomicInteger::get)
//            .tag("service", "demo").description("pass cases guage of demo")
//            .register(new SimpleMeterRegistry());
//
//    AtomicInteger passCases = Metrics.gauge("app.pass.cases.guage.value", init(), atomicInteger);

    @Override
    public void doInit(Object[] args) {

        while (true) {
            UT.Thread.sleepThread(100);
            if (System.currentTimeMillis() % 2 == 0) {
                passCases.addAndGet(100);
                System.out.println("ADD + " + passCaseGuage.measure() + " : " + passCases);
            } else {
                int val = passCases.addAndGet(-100);
                if (val < 0) {
                    passCases.set(1);
                }
                System.out.println("DECR - " + passCaseGuage.measure() + " : " + passCases);
            }
        }

    }

}